package com.atguigu.day05;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                // 数据流中一共有几个事件呢？
                // Watermark(-MAX)
                // "a 1"
                // Watermark(+MAX)
                .fromElements("a 1")
                .map(new MapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> map(String value) throws Exception {
                        String[] array = value.split(" ");
                        return Tuple2.of(array[0], Long.parseLong(array[1]) * 1000L);
                    }
                })
                .keyBy(r -> r.f0)
                .process(new KeyedProcessFunction<String, Tuple2<String, Long>, String>() {
                    @Override
                    public void processElement(Tuple2<String, Long> in, Context ctx, Collector<String> out) throws Exception {
                        ctx.timerService().registerEventTimeTimer(
                                in.f1 + 10 * 1000L
                        );

                        out.collect("输入数据：" + in + "，当前process并行子任务的水位线是：" + ctx.timerService().currentWatermark() + ", " +
                                "注册了一个定时器：" + (in.f1 + 10 * 1000L));
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        out.collect("定时器的时间戳是：" + timestamp + ", 当前process并行子任务的水位线是：" + ctx.timerService().currentWatermark());
                    }
                })
                .print();

        env.execute();
    }
}
